<?php
/**
 * Created by PhpStorm.
 * User: aiChenK
 * Date: 2019-02-12
 * Time: 13:23
 */

namespace Services\Msg\Core\Notice;

use Helpers\Main;
use Helpers\Page;
use Helpers\Tool;
use Services\Login\Login;
use Services\Msg\Models\Notice;

class Finder
{

    private $enum = [
        'type'  => [
            Creator::TYPE_INFO    => '<div class="grid-cell-text-bg-gray">普通</div>',
            Creator::TYPE_SUCCESS => '<div class="grid-cell-text-bg-green">成功</div>',
            Creator::TYPE_WARNING => '<div class="grid-cell-text-bg-yellow">警告</div>',
            Creator::TYPE_ERROR   => '<div class="grid-cell-text-bg-red">错误</div>',
        ],
        'level' => [
            Creator::LEVEL_NORMAL    => '<div class="grid-cell-text-bg-gray">一般</div>',
            Creator::LEVEL_IMPORTANT => '<div class="grid-cell-text-bg-yellow">重要</div>',
            Creator::LEVEL_EMERGENCY => '<div class="grid-cell-text-bg-red">紧急</div>',
        ],
    ];

    /**
     * 获取消息列表
     *
     * @param $page
     * @param $size
     * @param array $params
     * @param array $option
     * @return array
     *
     * create by ck 20190125
     */
    public function list($page, $size, $params = [], $option = [])
    {
        //处理条件
        $condition = [];
        $isScrap   = Tool::getValue($params, 'isScrap');
        if (is_numeric($isScrap)) {
            $condition[] = "notice.isScrap = '{$isScrap}'";
        }
        $isRead = Tool::getValue($params, 'isRead');
        if (is_numeric($isRead)) {
            $condition[] = "target.isRead = '{$isRead}'";
        }
        $condition = implode(' AND ', $condition);
        $condition and $condition = 'AND ' . $condition;

        $userId = Login::getId();
        $sql    = "SELECT
                target.id,
                notice.id AS noticeId,
                notice.title,
                notice.content,
                notice.url,
                notice.type,
                notice.`level`,
                notice.viewMode,
                target.isRead,
                notice.isScrap,
                notice.createAt,
                notice.createBy
            FROM `XHRemind_NoticeTarget` AS target
            LEFT JOIN `XHRemind_Notice` AS notice ON target.noticeId = notice.id
            WHERE
                target.isDel = 0
            AND notice.isDel = 0
            AND target.targetId = {$userId}
            {$condition}
            ORDER BY notice.id DESC";
        $data   = Page::runSqlPage($sql, $page, $size);

        //处理显示信息
        Tool::runTimestamp($data['rows'], ['createAt' => 'createAt']);
        if (Tool::getValue($option, 'enum', true) !== false) {
            foreach ($data['rows'] as &$row) {
                $style = [];
                if (!$row['isRead']) {
                    $style[] = 'font-weight: bold;';
                }
                if ($row['isScrap']) {
                    $style[] = 'text-decoration: line-through;';
                }
                $style        = implode(' ', $style);
                $row['title'] = "<div style='{$style}'>{$row['title']}</div>";
            }
            unset($row);
            Tool::runEnum($data['rows'], $this->enum);
        }
        if (Tool::getValue($option, 'user', true) !== false) {
            Main::runUserName($data['rows'], ['createBy' => 'createBy']);
        }
        return ['total' => $data['total'], 'rows' => $data['rows']];
    }

    /**
     * 获取未读消息
     *
     * @param int $num
     * @return mixed
     *
     * create by ck 20190118
     * modify by ck 20190125    调用主列表
     */
    public function unreadList(int $num = 5)
    {
        return $this->list(
            1,
            $num,
            ['isScrap' => 0, 'isRead' => 0],
            ['enum' => false, 'user' => false]
        );
    }

    /**
     * 根据id获取消息详情
     *
     * @param int $id
     * @return array
     * @throws \Exception
     *
     * create by ck 20190122
     */
    public function detail(int $id)
    {
        $info = Notice::findFirst([
            'columns'    => ['id', 'title', 'content', 'url', 'type', 'viewMode', 'level', 'isScrap'],
            'conditions' => 'isDel = 0 AND id = :id:',
            'bind'       => ['id' => $id]
        ]);
        if (!$info) {
            throw new \Exception('该消息不存在或已被删除');
        }
        if ($info->isScrap) {
            throw new \Exception('该消息已失效');
        }
        return $info->toArray();
    }
}
